package com.dong.mcd.util;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class ParseUtil {

	/**
	 * 序列sql参数
	 * @return
	 */
	public static List<String> findProp(String sql){
		String wrapStr = "#";
		List<String> paramList = new ArrayList<String>();
		while (true) {
			int _idxStart = sql.indexOf(wrapStr,-1);
			if (_idxStart == -1)
				break;
			int _idxEnd = sql.indexOf(wrapStr, _idxStart+1);
			if (_idxEnd == -1)
				break;
			String prop = sql.substring(_idxStart+1, _idxEnd);
			paramList.add(prop);
			sql = sql.replaceFirst(wrapStr+prop+wrapStr, "?");
		}
		return paramList;
	}
	
	/**
	 * 格式化sql参数
	 * @return
	 */
	public static String formartSql(String sql,Map<String, Object> map){
		String wrapStr1 = "$";
		String sql1 = sql;
		while (true) {
			int _idxStart = sql1.indexOf(wrapStr1,-1);
			if (_idxStart == -1)
				break;
			int _idxEnd = sql1.indexOf(wrapStr1, _idxStart+1);
			if (_idxEnd == -1)
				break;
			String prop = sql1.substring(_idxStart+1, _idxEnd);
			sql1 = sql1.replaceFirst("\\"+wrapStr1+prop+"\\"+wrapStr1, map.get(prop)+"");
		}
		return sql1;
	}
	
	/**
	 * 格式化sql参数
	 * @return
	 */
	public static String formartSql(String sql,Object map) throws Exception{
		String wrapStr1 = "$";
		String sql1 = sql;
		Class<?> class1 = map.getClass();
		while (true) {
			int _idxStart = sql1.indexOf(wrapStr1,-1);
			if (_idxStart == -1)
				break;
			int _idxEnd = sql1.indexOf(wrapStr1, _idxStart+1);
			if (_idxEnd == -1)
				break;
			String prop = sql1.substring(_idxStart+1, _idxEnd);
			String getMethodName = "get"+prop.substring(0, 1).toUpperCase()
							+prop.substring(1, prop.length());
			Method method = class1.getMethod(getMethodName);
			if ( method != null){
				sql1 = sql1.replaceFirst("\\"+wrapStr1+prop+"\\"+wrapStr1,method.invoke(getMethodName)+"");
			}
			
		}
		return sql1;
	}
}
